package com.apobates.forum.thrones.admin.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.entity.Board;
import com.apobates.forum.core.entity.TopicCategory;
import com.apobates.forum.core.service.BoardService;
import com.apobates.forum.core.service.BoardTopicCategoryIndexService;
import com.apobates.forum.core.service.TopicCategoryService;
import com.apobates.forum.thrones.admin.controller.form.BoardTopicCategoryForm;
import com.apobates.forum.thrones.admin.controller.helper.AdminUtils;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.TipMessage;

/**
 * 版块话题类型
 *
 * @author xiaofanku@live.cn
 * @since 20190910
 */
@Controller
@RequestMapping(value = "/board/category")
public class AdminBoardCategoryController {
    @Autowired
    private BoardTopicCategoryIndexService boardTopicCategoryIndexService;
    @Autowired
    private BoardService boardService;
    @Autowired
    private TopicCategoryService topicCategoryService;
    
    //已经关联的列表
    @GetMapping(path = "/")
    public String listPage(
            @RequestParam("board") long boardId,
            HttpServletRequest request,
            Model model) {
        Board boardObj = boardService.get(boardId).orElseThrow(()->new ResourceNotFoundException("版块不存在或暂时无法访问"));
        List<TopicCategory> rs = boardTopicCategoryIndexService.getAllByBoard(boardObj.getVolumesId(), boardObj.getId()).collect(Collectors.toList());
        model.addAttribute("rs", rs);
        model.addAttribute("board", boardObj);
        return "admin/board_category/index";
    }
    
    //关联
    @GetMapping(path = "/relative")
    public String relativeForm(
            @RequestParam("board") long boardId,
            @RequestParam("volume") int boardGroupId,
            HttpServletRequest request,
            Model model) {
        BoardTopicCategoryForm form = new BoardTopicCategoryForm();
        form.setBoard(boardId + "");
        form.setVolumes(boardGroupId + "");
        model.addAttribute("form", form);
        return "admin/board_category/edit";
    }
    //可以进行关联的话题类型,主要是防止重复关联内置的话题类型(举报|意见反馈)
    @GetMapping(path = "/rawdata.json")
    @ResponseBody
    public Map<Integer, String> getRelativeTopicCategories(HttpServletRequest request, Model model) {
        Set<Integer> relatived = boardTopicCategoryIndexService.getAllRelativeRecords();
        if (null == relatived) {
            relatived = new HashSet<>();
        }
        final Set<Integer> tmp = Set.copyOf(relatived);
        return topicCategoryService.getAssociates().filter(tc->!tmp.contains(tc.getId())).collect(Collectors.toMap(TopicCategory::getId, TopicCategory::getNames));
    }
    
    @PostMapping(path = "/relative")
    public String relativeAction(
            @ModelAttribute("form") BoardTopicCategoryForm form,
            HttpServletRequest request,
            Model model) {
        List<Integer> categoryIdList = AdminUtils.toIntegerList(form.getCategory());
        if (categoryIdList == null || categoryIdList.isEmpty()) {
            model.addAttribute("errors", "没有可供使用的话题类型");
            model.addAttribute("form", form);
            return "admin/board_category/edit";
        }
        //
        int boardGroupId = form.getIntegerVolumesId();
        long boardId = form.getLongBoardId();
        if (boardGroupId <= -1 || boardId < 0) { //0 :默认版块组, >0
            model.addAttribute("errors", "缺少参数或参数不被接受");
            model.addAttribute("form", form);
            return "admin/board_category/edit";
        }
        //
        int records = boardTopicCategoryIndexService.create(boardGroupId, boardId, categoryIdList);
        if (records > 0) {
            return "redirect:/board/category/?board=" + boardId;
        }
        model.addAttribute("errors", "版块关联话题类型操作失败");
        model.addAttribute("form", form);
        return "admin/board_category/edit";
    }
    
    //解关联
    @PostMapping(path = "/remove", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removeTagAction(
            @RequestParam("board") long boardId,
            @RequestParam("category") int topicCategoryId,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.of(()->boardTopicCategoryIndexService.deleteForTopic(boardId, Arrays.asList(topicCategoryId)) == 1).success("版块与话题类型的关联删除成功").error("操作失败");
    }
    
    //检查举报和反馈模块是否关联到了某版块
    @GetMapping(path = "/protect", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage nativeRelativeReport(HttpServletRequest request, Model model) {
        Set<Integer> relatived = boardTopicCategoryIndexService.getAllRelativeRecords();
        //哪个未关联
        if (relatived == null || relatived.isEmpty()) { //都没关联
            return TipMessage.ofError("举报和意见反馈功能正常使用需要进行版块关联");
        }
        String unRelativeCategoryTitle = null;
        if (!relatived.contains(TopicCategory.feedback().getId())) {
            unRelativeCategoryTitle = TopicCategory.feedback().getNames();
        }
        if (!relatived.contains(TopicCategory.report().getId())) {
            unRelativeCategoryTitle = TopicCategory.report().getNames();
        }
        if (unRelativeCategoryTitle == null) { //都关联了
            return TipMessage.ofSuccess("OK");
        }
        return TipMessage.ofError(unRelativeCategoryTitle + "功能正常使用需要进行版块关联");
    }
}